import * as React from 'react' ;
import ReactDOM from 'react-dom' ;
import classNames from 'classnames' ;

interface DivProps extends React.HTMLProps<HTMLDivElement> {
  // Ideally we would allow all data-* props but this would depend on https://github.com/microsoft/TypeScript/issues/28960
  'data-testid'?: string;
}

export interface NoticeProps {
  prefixCls: string ;
  style?: React.CSSProperties ;
  className?: string ;
  duration?: number | null ;
  children?: React.ReactNode ;
  updateMark?: string ;
  /** Mark as final key since set maxCount may keep the key but user pass key is different */
  noticeKey: React.Key ;
  closeIcon?: React.ReactNode ;
  closable?: boolean ;
  props?: DivProps ;
  onClick?: React.MouseEventHandler<HTMLDivElement> ;
  onClose?: (key: React.Key) => void ;
}

class Notice extends React.Component<NoticeProps> {
  static defaultProps = {
    onClose() {},
    duration: 1.5,
  };

  closeTimer: number | null = null ;

  componentDidMount() {
    // 挂载时开始计时器
    this.startCloseTimer();
  }

  componntWillUnmount() {
    // 卸载时销毁计时器
    this.clearCloseTimer();
  }

  close = (e?: React.MouseEvent<HTMLAnchorElement>) => {
    const { onClose, noticeKey } = this.props ;
    if(e) {
      e.stopPropagation();
    }
    this.clearCloseTimer();
    if(onClose) {
      onClose(noticeKey);
    }
    
  }

  startCloseTimer = () => {
    // 开始计时器
    if(this.props.duration) {
      this.closeTimer = setTimeout(()=>{
        this.close();
      },this.props.duration*1000);
    }
  }

  clearCloseTimer = () => {
    // 销毁计时器
    if(this.closeTimer){
      clearTimeout(this.closeTimer);
      this.closeTimer = null ;
    }
  }

  render() {
    const {
      prefixCls,
      className ,
      closable ,
      closeIcon ,
      style,
      onClick,
      children ,
    } = this.props;
    const componentClass = `${prefixCls}-notice` ;
    const node = (
      <div
        className={
          classNames(
            componentClass,
            className,
            {
              [`${componentClass}-closable`]: closable,
            }
          )
        }
        style={style}
        onMouseEnter={this.clearCloseTimer}
        onMouseLeave={this.startCloseTimer}
        onClick={onClick}
      >
        <div className={`${componentClass}-content`}>
          {children}
        </div>
        {
          closable
          &&
          <a
            tabIndex={0} //规定元素的 tab 键控制次序
            onClick={this.close}
            className={`${componentClass}-close`}
          >
            {
              closeIcon || <span className={`${componentClass}-close-x`}/>
            }
          </a>
        }
      </div>
    );

    return node ;
  }

}

export default Notice ;